package com.example.javaairportflightanalysis.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.example.javaairportflightanalysis.common.ApiRestResponse;
import com.example.javaairportflightanalysis.common.LoginResult;
import com.example.javaairportflightanalysis.domin.dto.UserDto;
import com.example.javaairportflightanalysis.domin.userpojo.User;
import com.example.javaairportflightanalysis.exception.MyExceptionEnum;
import com.example.javaairportflightanalysis.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author shen
 */
@CrossOrigin(originPatterns = "*",allowCredentials = "true")
@RestController
@Slf4j
@RequestMapping("/users")
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @SaIgnore
    public ApiRestResponse register(@RequestBody UserDto userDto){
        String password = userDto.getPassword();
        String userName = userDto.getUsername();
        if (ObjectUtils.isEmpty(userName)){
            return ApiRestResponse.error(MyExceptionEnum.NEED_USER_NAME);
        }
        if (ObjectUtils.isEmpty(password)){
            return ApiRestResponse.error(MyExceptionEnum.NEED_PASSWORD);
        }
        //密码长度不能少于六位
        if (password.length()<6){
            return ApiRestResponse.error(MyExceptionEnum.PASSWORD_TO_SHORT);
        }
        userService.register(userDto);
        return ApiRestResponse.success();
    }

    @PostMapping("/logout")
    @SaIgnore
    public ApiRestResponse logout(){
        StpUtil.logout(StpUtil.getLoginId());
        return ApiRestResponse.success("用户退出成功");
    }

    @PostMapping("/login")
    @SaIgnore
    public ApiRestResponse login(@RequestBody UserDto userDto, HttpServletRequest request){
            String password = userDto.getPassword();
            String userName = userDto.getUsername();
            User login = userService.login(userName, password);
        StpUtil.login(login.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        List<String> permissionList = StpUtil.getPermissionList();
        List<String> roleList = StpUtil.getRoleList();
        // 把权限码集合添加到响应对象中
        LoginResult loginResult = new LoginResult();
        loginResult.setTokenInfo(tokenInfo);
        loginResult.setPermissionList(permissionList);
        loginResult.setRoleList(roleList);
        loginResult.setUserImg(login.getImg());
        System.out.println("123456:"+roleList+"======="+loginResult);
//        RedisTemplate redisTemplate = new RedisTemplate<>();
//        redisTemplate.boundValueOps("loginId").set(login.getId());
        request.getSession().setAttribute("LoginId",login.getId());
        System.out.println("userController:"+login.getId());
        System.out.println("userController-requests:"+request.getSession().getAttribute("LoginId"));
        return ApiRestResponse.success(loginResult);
    }

    @SaCheckPermission(value = "USER_SELECT", orRole = "ROLE_ADMIN")
    @GetMapping("/findAllUser")
    public ApiRestResponse findAllUser(){
        List<User> users = userService.findAllUser();
        return ApiRestResponse.success(users);
    }

    @SaCheckPermission(value = "USER_ADD", orRole = "ROLE_ADMIN")
    @PostMapping("/addUser")
    public ApiRestResponse addUser(@RequestBody User user){
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = formatter.format(date);
        String updateTime = formatter.format(date);
        user.setCreateTime(createTime);
        user.setUpdateTime(updateTime);
        user.setPassword(BCrypt.hashpw(user.getPassword(),BCrypt.gensalt(10)));
        userService.addUser(user);
        return ApiRestResponse.success();
    }

    @SaCheckPermission(value = "USER_DELETE", orRole = "ROLE_ADMIN")
    @GetMapping("/deleteUser")
    public ApiRestResponse deleteUser(@RequestParam Integer id){
        userService.deleteUser(id);
        return ApiRestResponse.success();
    }

    @SaCheckPermission(value = "USER_UPDATE", orRole = "ROLE_ADMIN")
    @PostMapping("/updateUser")
    public ApiRestResponse updateUser(@RequestBody User user){
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updateTime = formatter.format(date);
        user.setUpdateTime(updateTime);
        userService.updateUser(user);
        return ApiRestResponse.success();
    }
}
